<?php
/**
 * 商品验证器
 */

namespace app\admin\validate;


use think\facade\Log;
use think\Validate;

class Goods extends Validate
{

    protected $rule = [
        "title|商品名称" => "require|max:50",
        "cate_id|一级分类" => "require",
        "cate_id2|二级分类" => "require",
        "second_title|二级名称" => "max:50",
//        "stock|库存" => "require|egt:0|integer",
        "price|价格" => "require|float|egt:0",
        "attr_status|规格状态" => "checkAttr",
        'image|展示图' => "require",
        "swiper_image|轮播图" => "checkSwiper",
        "sales_num|销量" => "number|egt:0",
        "baodan_status|报单状态" => "checkBaodan"
    ];

    protected function checkBaodan($val, $rule, $data = [])
    {
        if ($val == 1) {
            if (!isset($data['baodan_type']))
                return "您还未选择报单类型";
        }
        return true;
    }

    /**
     * 验证轮播图
     */
    protected function checkSwiper($val, $rule, $data = [])
    {
        if (empty($val)) {
            return '轮播图不能为空';
        } else {
            return true;
        }
    }

    /**
     * 验证规格信息
     * @param $val
     * @param $data
     * @return bool|string
     */
    protected function checkAttr($val, $rule, $data = [])
    {

        //是否使用多规格，如果没使用则不需验证规格信息
        if ($val == 0) {
            return true;
        } else {
            if (!isset($data['attr_detail']) || empty($data['attr_detail'])) {
                return "规格不能为空";
            } else {
                $attr_detail = $data['attr_detail'];
                foreach ($attr_detail as $item) {
                    if (empty($item['price']) || empty($item['ori_price']) || empty($item['stock'])) {
                        return '规格存在未填项，请填写完整后提交';
                    }
                }
                return true;
            }
        }
    }


}